/**
 * website
 * com.inmaytide.website.utils.office
 * AbstractExcelUtils.java
 * May 27, 2016 2:32:14 PM
 */
package com.inmaytide.website.utils.office;

import com.inmaytide.website.utils.ReflectUtils;
import com.inmaytide.website.utils.office.annotation.ExcelField;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;

/**
 * @author luomiao
 * @since May 27, 2016
 */
public abstract class AbstractExcelUtils {

    private Class<? extends java.io.Serializable> entityClass;

    private List<Field> columnFields;

    protected AbstractExcelUtils(Class<? extends java.io.Serializable> entityClass) {
        this.entityClass = entityClass;
        this.columnFields = ReflectUtils.findFieldsByAnnotation(entityClass, ExcelField.class);
        if (CollectionUtils.isEmpty(columnFields)) {
            throw new RuntimeException("Exportable properties not found!!!");
        }
        columnFields.forEach(f -> f.setAccessible(true));
    }

    public void setCellValue(Cell cell, Object value) {
        if (ObjectUtils.isEmpty(value)) {
            return;
        }
        if (value instanceof Integer) {
            cell.setCellValue((Integer) value);
        } else if (value instanceof Double) {
            cell.setCellValue((Double) value);
        } else if (value instanceof Boolean) {
            cell.setCellValue((Boolean) value);
        } else if (value instanceof Date) {
            cell.setCellValue((Date) value);
        } else {
            cell.setCellValue(value.toString());
        }
    }

    public Class<? extends java.io.Serializable> getEntityClass() {
        return entityClass;
    }

    public List<Field> getColumnFields() {
        return columnFields;
    }
}
